package me.shingohu.man.util;


import com.trello.rxlifecycle2.LifecycleTransformer;

import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import me.shingohu.man.base.BaseMVPActivity;
import me.shingohu.man.base.BaseMVPFragment;
import me.shingohu.man.mvp.IView;

/**
 * Created by jess on 11/10/2016 16:39
 */

public class RxUtils {

    public static <T> LifecycleTransformer<T> bindToLifecycle(IView view) {
        if (view != null) {
            if (view instanceof BaseMVPActivity) {
                return ((BaseMVPActivity) view).<T>bindToLifecycle();
            } else if (view instanceof BaseMVPFragment) {
                return ((BaseMVPFragment) view).<T>bindToLifecycle();
            } else {
                throw new IllegalArgumentException("view isn't activity or fragment");
            }
        } else {
            throw new IllegalArgumentException("view has deAttach");
        }
    }


    /**
     * 倒计时
     * @param time
     * @return
     */
    public static Observable<Integer> countdown(int time) {
        if (time < 0) time = 0;

        final int countTime = time;
        return Observable.interval(0, 1, TimeUnit.SECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .map(aLong -> countTime - aLong.intValue())
                .take(countTime + 1);

    }


}
